package com.tuanzi.loan.web.bean;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tuanzi.loan.business.service.system.SystemUserService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.security.AuthenticationFailureType;
import com.tuanzi.loan.web.configuration.JSFBean;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Ray 2017/09/21
 */
@Data
@Debug
@Slf4j
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoginBean extends JSFBean {

	private static final long serialVersionUID = 4200603739171913420L;

	@Autowired
	private SystemUserService userService;

	private String username;
	private String password;
	private boolean rememberMe;

	private String errorMessage;

	public void login() {
		FacesContext facesContext = getFacesContext();
		ExternalContext externalContext = facesContext.getExternalContext();
		RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest())
				.getRequestDispatcher("/login-process?username=" + username + "&password=" + password + "&remember-me=" + rememberMe);
		try {
			dispatcher.forward((ServletRequest) externalContext.getRequest(), (ServletResponse) externalContext.getResponse());
		} catch (Exception e) {
			log.error("Cannot forward to /process", e);
		}
		facesContext.responseComplete();
	}

	@PostConstruct
	public void init() {
		String failureType = getParamFromRequest("failureType");
		if (StringUtils.isNotBlank(failureType)) {
			errorMessage = AuthenticationFailureType.valueOf(failureType).getMessage();
		}
	}

}
